const OFFSET = 130;//顶部偏移量
const DURATION = 500;//动画持续时间

// 创建一个弱映射
const map = new WeakMap();

//初始化一个观察者
const ob = new IntersectionObserver((entries) => {
	for ( const entry of entries) {
		if ( entry.isIntersecting ) {
			const animation = map.get(entry.target);
			if ( animation ) {
				animation.play();
				ob.unobserve(entry.target);
			}
		}
	}
});

const belowViewport = ( el ) => {
	const rect = el.getBoundingClientRect();
	return rect.top > window.innerHeight;
}

export default {
	mounted(el) {
		//判断元素是否在视口内
		if ( !belowViewport(el)) {
			return ;
		}
		
		//实现上划动画
		// el.animation(关键帧, 动画配置);
		const animation  = el.animate([
			{
				transform: `translateY(${OFFSET}px)`,
				opacity: 0.5,
			},
			{
				transform: "translateY(0)",
				opacity: 1
			}
		], {
			duration: DURATION,
			easing: "ease-in",
			fill: "forwards"
		});
		animation.pause();//暂停动画
		console.log("mounted");
		
		ob.observe(el);//观察当前元素
		map.set(el, animation);
		
	},
	unmounted(el) {
		console.log("unmounted");
		ob.unobserve(el);
	}
}